import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter,Switch,Route, } from 'react-router-dom';
import { List, Tools, ActionSheet, Modal, Bubble,Icon,Checkbox,Flex } from 'weaver-mobile';
import { Form, RouteLayout } from 'weaver-mobile-page';
// import { toJS } from 'mobx'
import Create from '../create/index';
import * as API from '../../api/create'
const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const store = [
  'viewWorkplanStore',
  'createStore',
  'calendarStore',
  'workplanViewListStore'
];
@inject(...store)

@withRouter
@observer
class BaseView extends React.Component {
  constructor() {
    super();
    this.state = {
      clicked: 'none',
      mycheck: 0
    }
  }
  componentDidMount() {
    let {getPreview,isfromchatshare,sharer} = this.props.viewWorkplanStore;
    let params = {};
    if(isfromchatshare === 1 || isfromchatshare === '1'){
      params.isfromchatshare = isfromchatshare;
      params.sharer = sharer;
    }
    getPreview(params);
  }

  componentWillUnmount() {
    // 卸载组件时，清空数据
    const {setParams,form,overWriteOpenDoc,overWriteOpenWF,openDocFunc,openWFFunc} = this.props.viewWorkplanStore;
    form.resetFields();
    setParams({btnGroup: []});
    //是否需要还原openLink中的doc和workflow
    if(overWriteOpenDoc){
      window.openLink&&window.openLink.openDocument&&(window.openLink.openDocument = openDocFunc);
    }
    if(overWriteOpenWF){
      window.openLink&&window.openLink.openWorkflow&&(window.openLink.openWorkflow = openWFFunc);
    }
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  getView = () => {
    let {getPreview,isfromchatshare,sharer} = this.props.viewWorkplanStore;
    let params = {};
    if(isfromchatshare === 1 || isfromchatshare === '1'){
      params.isfromchatshare = isfromchatshare;
      params.sharer = sharer;
    }
    getPreview(params);
  }

  getFields = () => {
    const { form, noRight, noSecretRight, noData} = this.props.viewWorkplanStore;
    const { isInit, conditioninfo,} = form;
    let groups = [];
    let allNoremind = false;
    if (form.formParams) { // 当开始时间和结束时间都为不提醒时，不显示提醒方式，开始前，结束前
      allNoremind = form.formParams.remindBeforeEnd == form.formParams.remindBeforeStart 
                    && form.formParams.remindBeforeStart == getLabel(19782,'不提醒');
    }
    if(!(noRight || noSecretRight || noData)) {
      if(isInit) {
        conditioninfo && conditioninfo.forEach((group) => {
          let fields = [];
          group.items.forEach((field) => {
            if (allNoremind&&(field.domkey[0] === 'remindBeforeEnd' || field.domkey[0] === "remindBeforeStart")) return;
            if(field.domkey[0] === 'meetingIDs') {
              fields.push(
                <Form.Item
                  key={field.domkey.join('__')}
                  form={form}
                  fieldConfig={field}
                  onChange={form.onChange}
                />
              );
            }else{
              fields.push(
                <Form.Item
                  key={field.domkey.join('__')}
                  form={form}
                  fieldConfig={field}
                  onChange={form.onChange}
                />
              );
            }
          });
          groups.push(
            // 分组
            <div className='fold-group' key={group.title}>
              <div className='fold-title' onClick={() => {this.handleToggle(group.title, !group.show)}}>
                {group.title}
                <Icon className="flod-icon" type={group.show ? 'up' : 'down'} />
              </div>
              <div className={`${group.show ? 'show' : 'hide'}`}>
                {fields}
              </div>
            </div>
          )
        });
      }
    }

    return groups;
  }

  handleToggle = (...arg) => {
    const {groupToggle} = this.props.viewWorkplanStore;
    groupToggle(...arg);
  }

  deleteWorkplan = (param, obj) => {
    const {getDeleteWorkplan, isSingelViewWorkplan,fromType, setParams, isSingleHasWorkplanId } = this.props.viewWorkplanStore;
    const {deleteWorkplanStoreList,freshCalendar} = this.props.calendarStore;
    deleteWorkplanStoreList(param); // 删除日程列表中的数据，防止删除日程后请求接口过慢导致，再次可以点击已被删除的日程，致使无权限打开日程
    getDeleteWorkplan({workid: param},(params) => { 
      if(isSingelViewWorkplan && fromType !== 'crm') {
        if(isSingleHasWorkplanId) {
          window.em && window.em.closeWindow();
        } else {
          this.goBack(params);
        }
      } else if(isSingelViewWorkplan && fromType === 'crm') {
        setParams({otherModuleCloseWP:true})
        this.goBack(params);
      } else {
        this.goBack(params);
      }
      freshCalendar(true);
      this.getWorkplanViewList();
    })
    obj.close();
    // this.props.history.go(-1)
  }

  getWorkplanViewList = () => {
    let pathName = this.props.location.pathname;
    if(pathName && pathName.indexOf('workPlanViewList') > -1 ) {
      const { getCalendarData } = this.props.workplanViewListStore;
      getCalendarData();
    }
  }

  goBack = (params)=>{
    const {isfromMessageCenter} = this.props.viewWorkplanStore;
    if(isfromMessageCenter === 1 || isfromMessageCenter === '1'){
      if(window.em){
        window.em.closeWindow();
      } 
    }else{
      this.props.history.go(params)
    }
  }

  finishWorkplan = () => {
    const { workplanid, getFinishWorkplan, isSingelViewWorkplan,fromType, setParams, isSingleHasWorkplanId } = this.props.viewWorkplanStore;
    const { freshCalendar } = this.props.calendarStore;
    let remind = this.mycheck;
    getFinishWorkplan({workid: workplanid,isRemind: remind}, (params) => {
      if(isSingelViewWorkplan && fromType !== 'crm') {
        if(isSingleHasWorkplanId) {
          window.em && window.em.closeWindow();
        } else {
          setParams({otherModuleCloseWP:true})
          this.goBack(params);
        }
      } else if(isSingelViewWorkplan && fromType === 'crm') {
        setParams({otherModuleCloseWP:true})
        this.goBack(params);
      }else{
        this.goBack(params);
      }
      freshCalendar(true);
      this.getWorkplanViewList();
    })
    // this.props.history.go(-1)
  }

  onMethodClick = (method) => {
    const {workplanid,isCreater,fromType} = this.props.viewWorkplanStore;
    if(method==='doEdit') {
      const { setParams } = this.props.createStore;
      setParams({isEdit: true, workpalnID: workplanid, fromType:fromType})
      this.props.history.push("create")
    }
    let contentDom = null;
    let _this = this;
    _this.mycheck = 0;
    if(isCreater){
      contentDom = (
        <div>
          <div>{getLabel(387046,'确认完成吗？')}</div>
          <div>
            <Flex>
              <Flex.Item>
                <AgreeItem data-seed="logId" onChange={e => {
                    if(_this.mycheck == 0){
                      _this.mycheck = 1;
                    }else{
                      _this.mycheck = 0;
                    }
                    // console.log(_this.mycheck);
                  }
                }>
                  <a style={{fontSize: '14px',color: '#868686',}}>{getLabel(520269,'给接收人发送已完成的消息中心提醒')}</a>
                </AgreeItem>
              </Flex.Item>
            </Flex>
          </div>
        </div>
      )
    }else{
      contentDom = (
        <div>
          <div>{getLabel(387046,'确认完成吗？')}</div>
        </div>
      )
    }
    if(method ==='doFinish') {
      // alert(getLabel(15172,'系统提示'), getLabel(387046,'确认完成吗？'), [
        alert(getLabel(15172,'系统提示'), contentDom, [
        { text: getLabel(386789,'取消'), onPress: () => {}, style: 'default' },
        { text: getLabel(386788,'确定'), onPress: () => this.finishWorkplan() },
      ]);
    }
    if(method ==='doDelete') {
      if(workplanid.split('R').length > 1) {
        this.showActionSheetDelete()
      }else{
        const alertInstance = alert(getLabel(15172,'系统提示'), getLabel(15097,'确定要删除吗？'), [
          { text: getLabel(386789,'取消'), onPress: () => {}, style: 'default' },
          { text: getLabel(386788,'确定'), onPress: () =>  this.deleteWorkplan(workplanid, alertInstance)},
        ]);
      }
    }
    if(method==='doShare') {}
    if(method==='doLog') {}

  }

  getButtomGroup = () => {
    const { btnGroup } = this.props.viewWorkplanStore;
    let btngroup = [];
    if(btnGroup) {
      const temp = (i) => {
        let obj = {};
        obj.key = btnGroup[i].method;
        obj.text = btnGroup[i].title;
        obj.onClick = () => this.onMethodClick(btnGroup[i].method);
        btngroup.push(obj);
      };
      if(btnGroup.length > 3) {
        for(let i=0; i<2; i++) {
          temp(i);
        }
        btngroup.push(
          {
            key: 'domore',
            text: getLabel(131654,'更多'),
            onClick: () => {this.showActionSheet()},
          }
        );
      }else{
        for(let i=0; i<btnGroup.length; i++) {
          temp(i);
        }
      }
    }
    return btngroup;
  }

  showActionSheet = () => {
    const BUTTONS = [];
    const { btnGroup } = this.props.viewWorkplanStore;
    if( btnGroup ) {
      for(let i=0; i<btnGroup.length; i++) {
        let obj = {};
        obj.key = btnGroup[i].method;
        obj.content = btnGroup[i].title;
        obj.onClick = () => this.onMethodClick(btnGroup[i].method);
        BUTTONS.push(obj);
      }
      BUTTONS.push(
        {
          content: getLabel(386789,'取消'),
          onClick: () => {},
        },
      );
    }
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
    (buttonIndex) => {
      this.setState({ clicked: BUTTONS[buttonIndex] });
    });
  }

  deleteModuleWorkplan = (params) => {
    const {workplanid} = this.props.viewWorkplanStore;
    const {freshCalendar} = this.props.calendarStore;
    let param = {...params,workid: workplanid}
    API.deleteModulWorkplan(param).then(res => {
      if(res.api_status) {
        Bubble.success(getLabel(83472,'删除成功！'), 1)
        // setTimeout(() => {
        // }, 1000);
        this.props.history.go(-1);
        freshCalendar(true);
      }else{
        Bubble.success(getLabel(83473,'删除失败！'), 1)
      }
    });
  }
  
  showActionSheetDelete = () => {
    const {selectDate,} = this.props.calendarStore;
    const BUTTONS = [
      {
        content: getLabel(391129,'仅删除此日程'),
        onClick: () => this.deleteModuleWorkplan({delDate: selectDate}),
      },
      {
        content: getLabel(391068,'同时删除所有将来日程'),
        onClick: () => this.deleteModuleWorkplan(),
      },
      {
        content: getLabel(386789,'取消'),
        onClick: () => {},
      },
    ];
 
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
    (buttonIndex) => {
      this.setState({ clicked: BUTTONS[buttonIndex] });
    });
  }

  render() {
    const { btnGroup,noRight } = this.props.viewWorkplanStore;
    let H = window.innerHeight;
    let bottomGroup = this.getButtomGroup();
    let btnHeight = btnGroup.length>0 ? 47*window.getThemeVars()['hd'] : 0;
    let Height = noRight ? 0 : 45*window.getThemeVars()['hd'];
    return (
      <div style={{height: '100%'}}>
        <div className={noRight? 'scroll-auto-noright' :'scroll-auto'} style={{bottom:bottomGroup.length>0?btnHeight:'0px'}}>
          <List>
            {/* <Form store={form} /> */}
            {this.getFields()}
          </List>
        </div>
        {!noRight && <div className="detail-footer">
          <ButtonGroup data={bottomGroup}/>
        </div>}
        <Switch>
          <Route
            key="edit"
            path={`/:type/create`}
            render={()=>(
              <div id="edit">
                <Create />
              </div>
            )}
          />
        </Switch>
      </div>
    )
  }
}

export default BaseView;